package com.dlc.beijingrfid.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.view.View;
import android.widget.TextView;
import butterknife.BindView;
import com.dlc.beijingrfid.R;
import com.dlc.beijingrfid.activity.ChuKuActivity;
import com.dlc.beijingrfid.activity.InventoryCategoryActivity;
import com.dlc.beijingrfid.activity.MainActivity;
import com.dlc.beijingrfid.activity.OrderManageActivity;
import com.dlc.beijingrfid.activity.QueryRfidActivity;
import com.dlc.beijingrfid.activity.ReWashActivity;
import com.dlc.beijingrfid.activity.ScanSettingActivity;
import com.dlc.beijingrfid.base.BaseFragment;
import com.dlc.beijingrfid.helper.DBManager;
import com.dlc.beijingrfid.net.bean.HotelRfidBean;
import com.dlc.commonlibrary.ble.BleWorker;
import com.dlc.commonlibrary.dialog.DoResultDialog;
import com.dlc.commonlibrary.dialog.SureDialog;
import com.dlc.commonlibrary.dialog.YesNoDialog;
import com.dlc.commonlibrary.utils.ToastUtil;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by John on 2017/7/18.
 */

public class HomeFragment extends BaseFragment implements View.OnClickListener {
    @BindView(R.id.item_2)
    TextView item_2;
    @BindView(R.id.ruku)
    TextView ruku;
    @BindView(R.id.chuku)
    TextView chuku;
    @BindView(R.id.distribute_odd)
    TextView distribute_odd;
    @BindView(R.id.order_manage)
    TextView order_manage;
    @BindView(R.id.inventory_manage)
    TextView inventory_manage;
    @BindView(R.id.re_wash)
    TextView mReWash;
    @BindView(R.id.setPower)
    TextView mSetPower;

    private DoResultDialog doReadDialog, doResultDialog;
    private StringBuilder mStringBuilder;
    public static final String EXTRA_RFIDS = "rfids";
    public static final int chuku_equestCode = 200;
    private Handler mHandler = new Handler();
    private DBManager dbManager;
    private Class<? extends Activity> mClass;
    BleWorker mBleWorker = new BleWorker();

    @Override
    public void onCreateView() {
        setViewClickListener();
        doReadRFID();
        doResult();
        dbManager = DBManager.getInstance(getActivity());
        mBleWorker.setCallback(new BleWorker.ReadCallback() {
            @Override
            public void onReceiveData(ArrayList<String> rfList, int readNum) {
                doReadDialog.dismiss();
                doResultDialog.showResultAndDismiss(true, 1000);
                if (rfList.size() > 0) {
                    doResultDialog.dismiss();
                    Intent intent = new Intent(getActivity(), mClass);
                    intent.putExtra(EXTRA_RFIDS, rfList);
                    startActivityForResult(intent, chuku_equestCode);
                } else {
                    doResultDialog.setFailedText("讀取不到RFID");
                    doResultDialog.setFailedImage(R.mipmap.ic_error);
                    doResultDialog.showResultAndDismiss(false, 2000);
                }
            }

            @Override
            public void onDeviceDisconnected() {
                doReadDialog.dismiss();
                Intent intent = new Intent(getActivity(), MainActivity.class);
                intent.putExtra("type", "2");
                startActivity(intent);
            }

            @Override
            public void onErrorNumber(int number) {
                if (number > 0) {
                    showOneToast("存在长度小于14的标签" + number + "个");
                }
            }
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home;
    }

    private void setViewClickListener() {
        item_2.setOnClickListener(this);
        ruku.setOnClickListener(this);
        chuku.setOnClickListener(this);
        distribute_odd.setOnClickListener(this);
        order_manage.setOnClickListener(this);
        inventory_manage.setOnClickListener(this);
        mReWash.setOnClickListener(this);
        mSetPower.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.item_2:
                ((MainActivity) getActivity()).scanQRCode(MainActivity.REQUEST_BUCAO);
                break;
            case R.id.chuku:
                //((MainActivity)getActivity()).scanQRCode(MainActivity.REQUEST_CHUKU);
                //startActivity(new Intent(getActivity(),ChuKuActivity.class));

                mClass = ChuKuActivity.class;
                setDbManager();
                break;
            case R.id.re_wash:
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getData();
                        mClass = ReWashActivity.class;
                        //  test();
                    }
                }, 500);
                break;
            case R.id.ruku:
                ((MainActivity) getActivity()).scanQRCode(MainActivity.REQUEST_RUKU);
                break;
            case R.id.distribute_odd:
                // startActivity(new Intent(getActivity(), DistributeOddActivity.class));
                startActivity(new Intent(getActivity(), QueryRfidActivity.class));
                break;
            case R.id.order_manage:
                startActivity(new Intent(getActivity(), OrderManageActivity.class));
                break;
            case R.id.inventory_manage:
                startActivity(new Intent(getActivity(), InventoryCategoryActivity.class));
                break;
            case R.id.setPower:
                startActivity(new Intent(getActivity(), ScanSettingActivity.class));
                break;
        }
    }

    /**
     * 检查自动清空前一天数据
     */
    private void setDbManager() {
        List<HotelRfidBean> list = dbManager.queryLabelList();
        if (list.size() > 0) {
            showWaitingDialog("正在清理前一天", false);
            dbManager.deleteLabel();
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    dismissWaitingDialog();
                    isDeleteDb();
                }
            }, 2000);
        } else {
            isDeleteDb();
        }
    }

    /**
     * 是否清空保存的数据
     */
    private void isDeleteDb() {
        List<HotelRfidBean> list = dbManager.queryLabelList();

        if (list.size() > 0) {
            SureDialog sureDialog = new SureDialog(getContext(), "是否清空未提交的数据");
            sureDialog.setOnCallBackListener(new SureDialog.OnCallBack() {
                @Override
                public void sure() {
                    YesNoDialog yesNoDialog = new YesNoDialog(getContext(), "是否清空未提交的数据");
                    yesNoDialog.setOnCallBackListener(new YesNoDialog.OnCallBack() {
                        @Override
                        public void sure() {
                            dbManager.deleteHotelLabelAll();
                            mHandler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    getData();
                                    ToastUtil.show(getContext(), "已清空");
                                }
                            }, 1000);
                        }

                        @Override
                        public void cancle() {
                            getData();
                        }
                    });
                }

                @Override
                public void cancle() {

                    getData();
                    //test();
                }
            });
        } else {
            getData();
            //test();
        }
    }

    private void test() {
        ArrayList<String> rfids = new ArrayList<>();
        rfids.add("0001C4D95F2F");
        rfids.add("0001C4D8B86B");
        rfids.add("00393B7B2C24");
        if (rfids.size() > 0) {
            doResultDialog.dismiss();
            Intent intent = new Intent(getActivity(), mClass);
            intent.putExtra(EXTRA_RFIDS, rfids);
            startActivityForResult(intent, chuku_equestCode);
        } else {
            doResultDialog.setFailedText("讀取不到RFID");
            doResultDialog.setFailedImage(R.mipmap.ic_error);
            doResultDialog.showResultAndDismiss(false, 2000);
        }
    }

    private void getData() {
        doReadDialog.showWorking(true);
        mBleWorker.check();
    }

    //private void doData(String data){
    //    rfidsList.add(data);
    //    LogPlus.e("蓝牙数据=" + data+"==蓝牙数据 count=" + rfidsList.size() + "");
    //}
    //
    //private void judgeData(final Class<? extends Activity> cls) {
    //    runOnUiThread(new Runnable() {
    //        @Override
    //        public void run() {
    //            if (!isBleStop) {
    //                if (rfidsList.size() > 0) {
    //                    if (rfidsList.size() == cashCount || TYPE == 2) {//获取到的缓存区数量相等或者是直接获取缓存数据
    //                        ArrayList<String> mList = new ArrayList<>();
    //                        doReadDialog.dismiss();
    //                        doResultDialog.showResultAndDismiss(true, 1000);
    //                        for (String str : rfidsList) {
    //                            if (str.length() > 14) {
    //                                str = str.substring(str.length() - 12, str.length());
    //                                mList.add(str);
    //                            }
    //                        }
    //                        Intent intent = new Intent(getActivity(), cls);
    //                        intent.putExtra(EXTRA_RFIDS, mList);
    //                        startActivityForResult(intent, chuku_equestCode);
    //                    } else {
    //                        //ToastUtil.show(getContext(),"获取的数量不对应，直接获取读到的缓存rfid");
    //                        TYPE = 2;
    //                        rfidsList.clear();
    //                        RRUA100API.getInstance(new Handler()).A100_getSyncTagList();
    //                    }
    //                } else {
    //                    doResultDialog.setFailedText("读取不到RFID");
    //                    doResultDialog.setFailedImage(R.mipmap.ic_error);
    //                    doResultDialog.showResultAndDismiss(false, 2000);
    //                }
    //            }else {
    //                showToast("未连接设备，跳到连接页面");
    //                Intent intent = new Intent(getActivity(),MainActivity.class);
    //                intent.putExtra("type", "2");
    //                startActivity(intent);
    //            }
    //        }
    //    });
    //
    //}

    private void doReadRFID() {
        doReadDialog = DoResultDialog.newDialog(getActivity())
            .setSuccessImage(R.mipmap.ic_success)
            .setSuccessText(getString(R.string.scan_over))
            .setButton("完成扫描", new DoResultDialog.OnClickButtonListener() {
                @Override
                public void onClickButton(DoResultDialog dialog) {
                    mBleWorker.cancelCheck();
                }
            });

        doReadDialog.setCancelable(false);
    }

    private void doResult() {

        doResultDialog = DoResultDialog.newDialog(getActivity())
            .setWorkingText(getString(R.string.commit_counting_result))
            .setSuccessImage(R.mipmap.ic_success)
            .setSuccessText(getString(R.string.commit_counting_result_success));

        doResultDialog.setCancelable(false);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //if (chuku_equestCode == requestCode){
        //    ArrayList<String> infoList = new ArrayList<String>();
        //
        //    infoList = data.getStringArrayListExtra("rfid");
        //   // savaDb(infoList);
        //}
    }


}
